package com.heima.kafka.sample;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Properties;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-10-25 10:43
 */
public class ConsumerQuickStart107 {

    public static void main(String[] args) {

        //构建properties对象，对kafka进行配置
        Properties properties = new Properties();
        //kafka地址
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"group1");

        //创建kafka生产者对象
        KafkaConsumer<String, String> consumer =
                new KafkaConsumer<String, String>(properties);

        //接收消息
        ArrayList<String> strings = new ArrayList<>();
        strings.add("itcast-107-3");

        consumer.subscribe(Collections.singletonList("itcast-107-3"));

        while (true){
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofSeconds(1));
            System.out.println(poll.count());
            for (ConsumerRecord<String, String> data : poll) {
                System.out.println(data.value());
                consumer.commitSync();
            }
        }


    }
}
